﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;

namespace FRW.Common
{
    public static class SerializeExtensions
    {
        public static void ToXMLFile(this object objToserialize, string filename)
        {
            StreamWriter sr = new StreamWriter(filename);
            sr.Write(objToserialize.ToXML());
            sr.Close();
        }

        public static string ToXML(this object objToSerialize)
        {
            XmlSerializer mySerializer = null;

            try
            {
                // Instantiate the Serializer with the type of object that is being deserialized.
                mySerializer = new XmlSerializer(objToSerialize.GetType());
                string xmlStr;

                // Serialize the object to xml
                using (MemoryStream ms = new MemoryStream())
                {
                    mySerializer.Serialize(ms, objToSerialize);

                    // Get XML as string
                    xmlStr = ASCIIEncoding.ASCII.GetString(ms.ToArray());
                }

                if (xmlStr == null || xmlStr.Length == 0)
                {
                    return String.Empty;
                }

                return xmlStr;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
